import { getStream } from '../Core/connect'
import * as MathUtils from '../Math/MathUtils'
import { Vector3 } from '../Math/Vector3'

export class Foliage{
    readonly type: string
    position: Vector3
    rotate: Vector3
    size: Vector3
    foliageType: number
    polygonList: Array<Vector3>
    uuid: string
    constructor(polygonList: Array<Vector3>, foliageType: number) {
        this.type = 'Foliage'
        this.foliageType = foliageType
        this.uuid = MathUtils.generateUUID()
        this.position = new Vector3(0, 0, 0)
        this.rotate = new Vector3(0, 0, 0)
        this.size = new Vector3(1, 1, 1)
        this.polygonList = polygonList
        this.init()
    }

    init() {
        const stream = getStream()
        const outList = this.getListToString(this.polygonList)
        const str = {
            foliageFunction: 'createFoliage',
            ids: `${this.type},${this.uuid}`, 
            position: `${this.position.x},${this.position.y},${this.position.z}`,
            rotate: `${this.rotate.x},${this.rotate.y},${this.rotate.z}`,
            size: `${this.size.x},${this.size.y},${this.size.z}`,
            positionList: [outList],
            foliageType: this.foliageType
        }
        stream.emitUIInteraction(str)
    }

    setFoliageBoundary(boundary: number) {
        const stream = getStream()
        const str = {
            foliageFunction: 'setFoliageBoundary',
            ids: `${this.uuid}`,
            boundary: boundary
        }
        stream.emitUIInteraction(str)
    }

    getListToString(positionList: Array<Vector3>) {
        let outList = ''
        for (const one of positionList) {
            outList += `[${one.x}`+ ',' + `${one.y}],`
        }
        outList = outList.slice(0, -1)
        outList = "[" + outList + "]"
        return outList
    }

    setLonLatPosition(position: Vector3){
        const stream = getStream()
        const getNewPositon = (data: string) => {
            const returnData = JSON.parse(data)
            if (returnData.ids === this.uuid) { 
                this.position = new Vector3(returnData.position.x, returnData.position.y, returnData.position.z)
                stream.removeResponseEventListener("getNewPositon")
            }
        }
        stream.addResponseEventListener("getNewPositon", getNewPositon)
        const str = {function: 'setLonLatPosition', ids: `${this.uuid}`,position:`${position.x},${position.y},${position.z}`}
        stream.emitUIInteraction(str)
    }

    setPosition(position: Vector3) {
        const stream = getStream()
        const str = {
            foliageFunction: 'setFoliagePosition',
            ids: `${this.uuid}`,
            position: `${position.x},${position.y},${position.z}`,
        }
        stream.emitUIInteraction(str)
    }

    delete() {
        const stream = getStream()
        const str = {function: 'deleteObject3D', ids: `${this.uuid}`}
        stream.emitUIInteraction(str)
	}

}